/*
Copyright (C) 2022-2024 Inspur Corp.

SPDX-License-Identifier: Apache-2.0
*/
package service

import (
	"icep/bean/entity"
	"icep/bean/model"
	"icep/common/constant"
	sort2 "sort"
)

func (is *IcepService) QueryMenuList(currentUserType string) []*model.MenuDetail {
	menus := make([]*entity.IcepMenu, 0)
	// 默认为管理员权限
	condition := "admin_access = '1'"
	if currentUserType == constant.UserTypePerson {
		condition = "person_access = '1'"
	}
	if currentUserType == constant.UserTypeOrg {
		condition = "org_access = '1'"
	}
	err := is.DbEngine.Where(condition).Find(&menus)
	if err != nil {
		log.Errorf("query menu list error: %s", err)
		return nil
	}
	treeMap := make(map[string]*model.MenuDetail, 0)
	// 遍历menus，转换为map。以唯一ID为key
	for _, v := range menus {
		treeMap[v.Id] = &model.MenuDetail{
			Id:        v.Id,
			MenuName:  v.MenuName,
			MenuLevel: v.MenuLevel,
			IsLeaf:    v.IsLeaf,
			MenuPath:  v.MenuPath,
			Seq:       v.Seq,
			MenuIcon:  v.MenuIcon,
			Menus:     []*model.MenuDetail{},
		}
	}
	treeDate := make([]*model.MenuDetail, 0)
	for _, v := range menus {
		if v.ParentId == "" {
			treeDate = append(treeDate, treeMap[v.Id])
		}
		if d, ok := treeMap[v.ParentId]; ok {
			d.Menus = append(d.Menus, treeMap[v.Id])
		}
		continue
	}
	for _, v := range menus {
		detail := treeMap[v.ParentId]
		if detail != nil && detail.Menus != nil {
			childrenSort(detail.Menus)
		}
	}
	parentSort(treeDate)
	return treeDate
}

func childrenSort(childern []*model.MenuDetail) {
	sort2.Slice(childern, func(i, j int) bool {
		return childern[i].Seq < childern[j].Seq
	})
}

func parentSort(treeDate []*model.MenuDetail) {
	sort2.Slice(treeDate, func(i, j int) bool {
		return treeDate[i].Seq < treeDate[j].Seq
	})
}
